app.controller('OperationDataTableController', OperationDataTableController);
function OperationDataTableController($scope, RESTService, $filter, $compile, $state, $modal, $timeout) {
    // define value
    $scope.searchKey = "";
    var state = stateCurrent($state.current.name);
    $scope.oldState = "";
    $scope.loadStarting = true;
    setState(state);
    // paging for service request
    $scope.dtOptions = {
        aaSorting: [],
        bFilter: false,
        bLengthChange: false,
        bSort: false,
        bStateSave: false,
        oLanguage: {
            sUrl: ("Cn" === $scope.locale ? "./l10n/datatables.Chinese.json" : "")
        },
        processing: true,
        serverSide: true,
        sAjaxDataProp: "data",
        ajax: function(data, callback) {
            if($scope.State != $scope.oldState) {
                $scope.servRequests = [];
                getCountServRequest();
                // prepare query variables
                var params = {
                    like: $scope.searchKey, pageNo: data.start / data.length + 1, pageSize: data.length
                };
                if ($scope.MedicalFlag == true) {
                    params.status = "waitope"
                }
                var sort = [], i;

                if (0 !== data.order.length) {
                    for (i in data.order) {
                        if (data.order.hasOwnProperty(i)) {
                            sort.push({
                                property: data.columns[data.order[i].column].data,
                                direction: data.order[i].dir.toUpperCase()
                            });
                        }
                    }

                    if (0 !== sort.length) {
                        params.sort = angular.toJson(sort);
                    }
                }

                if (3 <= data.search.value.length) {
                    params.filter = data.search.value;
                }
                // transmit to server
                if ($scope.ApiUrl != "" && $scope.ApiUrl != null) {
                    RESTService.getResponse("/rest/servreq/" + $scope.ApiUrl + "?" + $.param(params)).then(function(response) {
                        angular.forEach(response, function(item) {
                            item.No = $scope.servRequests.length + (params.pageNo * params.pageSize) - 9;
                            switch ($scope.State){
                                case "Business":
                                    item.isCanConfirm = (item.canConfirmByBusiness)?true:false;
                                    break;
                                case "CentDoc" :
                                    item.isCanConfirm = (item.canConfirmByCentDoc)?true:false;
                                    break;
                                case "Operator" :
                                    item.isCanConfirm = (item.canConfirmByOperator)?true:false;
                                    break;
                                case "Medical":
                                    item.isCanConfirm = (item.canSetOperated)?true:false;
                                    break;
                            }
                            $scope.servRequests.push(item);
                        });
                        $scope.loadStarting = false;
                        callback({
                            aaData: [], draw: data.draw, recordsTotal: $scope.rowCount, recordsFiltered: $scope.rowCount
                        });
                        $scope.dtInstance.find("td.dataTables_empty").parent().hide(); // small hack for "aaData: []"
                    });
                }
            }
        }, fnCreatedRow: function(row) {
            $compile(row)($scope);
        }, fnInitComplete: function() {
            $scope.$parent.dtInstance = this.fnSetFilteringDelay();
        }
    };
    // listen change for state
    $scope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
        if (fromState.name.indexOf('operation') >= 0 && toState.name.indexOf('operation') >= 0) {
            $scope.oldState = stateCurrent(fromState.name);
            $scope.searchKey =  '';
            var stateName = stateCurrent(toState.name);
            setState(stateName);
            if ($scope.oldState != '') {
                $timeout(function() {
                    if ($scope.loadStarting == false) {
                        $scope.loadStarting = true;
                        $scope.dtInstance.DataTable().ajax.reload();
                    }
                }, 500);
            }
        }
    });
    // action list
    $scope.startSearch = function() {
        reloadData();
    };
    function setState(state) {
        if (state != '') {
            if (state == "Medical") {
                $scope.State = state;
                $scope.ApiUrl = "getServReqs";
                $scope.ApiCountUrl = "getServReqsCount";
                $scope.ApiConfirmUrl = "setOperated";
                $scope.MedicalFlag = true;
            } else {
                $scope.State = state;
                $scope.ApiUrl = "getSR4ConfirmBy" + state;
                $scope.ApiCountUrl = "getSRC4ConfirmBy" + state;
                $scope.ApiConfirmUrl = "confirmBy" + state;
                $scope.MedicalFlag = false;
            }
            return true;
        }
    }

    function stateCurrent(state) {
        var res = state.split(".");
        switch (res[res.length - 1]) {
            case 'businessmanager':
                $scope.title = $filter('translate')('business.servreq.confirm_Business');
                return 'Business';
            case 'doctor':
                $scope.title = $filter('translate')('business.servreq.confirm_CentDoc');
                return 'CentDoc';
            case 'operator':
                $scope.title = $filter('translate')('business.servreq.confirm_Operator');
                return 'Operator';
            case 'medicaladmin':
                $scope.title = $filter('translate')('business.servreq.confirm_MedicalAdmin');
                return 'Medical';
        }
        return '';
    }

    function getCountServRequest() {
        if ($scope.ApiCountUrl != "" && $scope.ApiCountUrl != null) {
            var param = {
                like: $scope.searchKey
            };
            if ($scope.MedicalFlag == true) {
                param.status = "waitope"
            }
            RESTService.getResponse("/rest/servreq/" + $scope.ApiCountUrl + "?" + $.param(param)).then(function(response) {
                if (undefined !== response) {
                    $scope.rowCount = response[0].count;
                }
            });
        }
    }

    function reloadData() {
        $scope.dtInstance.DataTable().ajax.reload();
    }

    function finishConfirm(serv) {
        var param = {
            servReq_Id: serv.servReq_Id
        };
        if (serv.desc != null && serv.desc != '') {
            param.desc = serv.desc;
        }
        if (serv.amount_Operation != null && serv.amount_Operation != '') {
            param.amount_Operation = serv.amount_Operation;
        }
        RESTService.postResponse("/rest/servreq/" + $scope.ApiConfirmUrl + "?", param).then(function(response) {
            if (undefined !== response) {
                reloadData();
            }
        });
    }

    $scope.openConfirmPopup = function(serv) {
        $scope.SelectedRequest = serv;
        if ($scope.State == 'Operator' || $scope.State == 'CentDoc') {
            $scope.SelectedRequest.isShowDesc = true;
        }
        if ($scope.State == 'Business') {
            $scope.SelectedRequest.isShowAmountOperation = true;
        }
        var modalInstance = $modal.open({
            backdrop:'static',
            templateUrl: 'TakeDescription.html', controller: 'ModalInstanceCtrl', size: 'md', resolve: {
                items: function() {
                    return $scope.SelectedRequest;
                }
            }
        });
        modalInstance.result.then(function() {
            finishConfirm($scope.SelectedRequest);
            $scope.SelectedRequest = {};
        }, function() {
            $scope.SelectedRequest = {};
        });
    };

    $scope.open = function(attrs, model) {
        // model.scope = $scope;
        $modal.open(angular.extend({
            backdrop:'static',
            controller: "ModalInstanceCtrl", resolve: {
                items: function() {
                    return [Object(model)];
                }
            },
            scope : $scope
        }, attrs));
    };

    // share case
    $scope.sharePatient = function(a, b){
        var patient_Id = a.patient_Id ? a.patient_Id : a.patient_Id2;
        var params = {
            patient_Id:patient_Id
            ,friendId:b
        }
        console.log(params);
        RESTService.postResponse('/rest/chat/createChatMessageSharingPatient?', params).then(
            function (suc) {
                console.log(suc);
            });
    }
}